from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from Products.CMFPlone.utils import base_hasattr
import json 
import sys
from DateTime.DateTime import DateTime
import datetime
class ChapterListView(BrowserView):
    xml  = ViewPageTemplateFile("list_view.xml")
    page = ViewPageTemplateFile("list_view.pt")
    def __init__(self,context,request):
        self.context = context
        self.request = request
        self.status = 0
    def updatedChapters(self,date):
        results = []
        path = path='/'.join(self.context.getPhysicalPath())
        list = self.context.portal_catalog.searchResults(path=path,Type = "ComixChapter",modified = {"query": date, "range": "min"},review_state="published") 
        for item in list:
            results.append(item.getObject())
        return results
        
    def chapters(self):
        return self.context.searchList(None,type='ComixChapter')
    def formatListIDs(self,results):
        list = []
        for item in results:
            list.append(item.UID())
        return list
    # Params Status 1 new  2 popular 3 free
    def formatList(self,results):
        list = []
        num = 0
        for item in results:
            if item.price: # freebook does not add num
                num=num+1
            
            if self.status == 1:
                if item.price == None or item.price==0.0:
                    continue
                elif num<11:
                    pass
                else:
                    break
                
            elif self.status == 2:
                if item.price == None or item.price==0.0:
                    continue
                elif num<11:
                    continue
                else:
                    pass
            elif self.status == 3:
                if item.price == None or item.price==0.0: # None or 0.0
                    pass
                else:
                    continue
            else:
                pass
                
            descDict = {}
            descDict['id'] = item.UID()
            descDict['title'] = item.title
            descDict['minicover'] = '%s/cover_mini' % item.absolute_url()
            descDict['cover'] = '%s/cover' % item.absolute_url()
            if item.price != None:
                descDict['price'] = '%.2f' % item.price
            else:
                descDict['price'] = '0.00'
# add Status
            if item.price == None or item.price==0.0: # None or 0.0
                descDict['status'] = 3
            elif num<11:
                descDict['status'] = 1
            else:
                descDict['status'] = 2
                
            descDict['buy_status'] = 1
            descDict['level'] = 4
            description = item.Description()
            if len(description)<135:
                descDict['description'] =  description
            else:
                descDict['description'] = '%s...' % description.decode('utf8')[:43].encode('utf8')
            list.append(descDict)
        return list
        
    
    def __call__(self):
        if base_hasattr(self.request, 'status'):
            try:
                self.status = int(self.request.status)
            except:
                pass
                
        if base_hasattr(self.request, 'json'):
            if  base_hasattr(self.request, 'id'):
                uid = self.request.id
                series =  self.context.reference_catalog.lookupObject(uid)
                if series==None or type(series)!="ComixFolder":
                    return '{"Status":"Error","Message":"ID Invalid type=%s"}' % type(series)
                return json.dumps(self.formatList(series.getChapters()))
            elif base_hasattr(self.request, 'ids'):
                if base_hasattr(self.request, 'updated'):
                    try:
                        updated = self.request.updated
                        date = DateTime(updated)
                    except:
                        today = datetime.date.today()
                        onemonth = datetime.timedelta(days=7)
                        date = today - onemonth
                    return json.dumps( self.formatListIDs(self.updatedChapters(date) ) )
                else:
                    return json.dumps(self.formatListIDs(self.chapters()))
            else:
                return json.dumps(self.formatList(self.chapters()))
        elif base_hasattr(self.request, 'xml'):
            self.request.response.setHeader('Content-Type',
                                        'text/xml')
            return self.xml()
        else:
            return self.page()
        
        
class ChapterDetailView:
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def updated(self):
        path = path='/'.join(self.context.getPhysicalPath())
        today = datetime.date.today()
        onemonth = datetime.timedelta(days=7)
        date = today - onemonth        
        # TODO  'Date' replace 'modified' when released
        list = self.context.portal_catalog.searchResults(path=path,Type = "ComixChapter",modified = {"query": date, "range": "min"},review_state="published")
        return list
    
    def formatDetail(self,item):
        itemUrl = item.absolute_url()        
        descDict = {}
        descDict['id'] = item.UID()
        descDict['title'] =  item.title
        if item.price!=None:
            descDict['price'] = '%.2f' % item.price
        else:
            descDict['price'] = '0.00' 
        descDict['author'] = 'ePub'
        descDict['cover'] = '%s/cover' % itemUrl
        descDict['minicover'] = '%s/cover_mini' % itemUrl
        descDict['description'] =  item.Description()
        descDict['level'] = 4
        descDict['pages'] = len(item.objectIds())
        descDict['rating'] = '12+'
        descDict['buy_status'] = 1
        
        if item.price == None or item.price==0.0:
            descDict['status'] = 3
        else:
            #TODO  change code : if xxx in lists
            isNew = False
            list = self.updated()
            for newItem in list:
                if itemUrl == newItem.getURL():
                    descDict['status'] = 1
                    isNew = True
                    break
                else:
                    continue
            if isNew == False:
                descDict['status'] = 2
            
            
        # seriesId
        descDict['seriesid'] = item.getSeries().UID()
#       relateditems
#        list = item.getSeries().getChapters()[:3]
#        relatedItems = []
#        for relatedItem in list:
#            relatedDict = {}
#            relatedDict['id'] = relatedItem.UID()
#            relatedDict['minicover'] = '%s/cover_mini' % relatedItem.absolute_url()
#            relatedItems.append(relatedDict)
#        descDict['relatedChapters'] = relatedItems
        
        return descDict
        
    def __call__(self):
#        if base_hasattr(self.request, 'id'):
#            try:
                uid = self.request.id
                chapter =  self.context.reference_catalog.lookupObject(uid)
                if chapter==None:
                    return '{"Status":"Error","Message":"ID Null"}'
                
                return json.dumps(self.formatDetail(chapter))
                
#            except:
#                return '{"ERROR": %s}' % sys.exc_info()[0]
class ChapterPagesView:
    def __init__(self,context,request):
        self.context = context
        self.request = request
        self.chapter = None
    def __call__(self):
        uid = self.request.id
        self.chapter =  self.context.reference_catalog.lookupObject(uid)
        if self.chapter==None:
            return '{"Status":"Error","Message":"ID Null"}'
        
        if base_hasattr(self.request, 'json'):
            return json.dumps(self.formatPages())
        else:
            return '{"Status":"Error","Message":"Lack parameter json"}'
    def pages(self):
        return self.chapter.listFolderContents()
    def formatPages(self):
        pages=[]
        minipages=[]
        num = 0 
        for page in self.pages():
            pages.append(page.id)
            minipages.append('%s/mini.%s' % (page.id,page.id))
        descDict={}
        descDict['root'] = '%s' % self.chapter.absolute_url()
        descDict['pages'] = pages
        descDict['minipages'] = minipages
        descDict['xml'] = 'pages.plist'
        return descDict